import { mapState } from 'vuex'
import { cloneDeep } from 'lodash'
import { addTestDrive, testDrive } from '@/API/testDrive'
import { getOpenIdApi, sendMessageApi } from '@/API/home'
import { brand, brand_id, tmplIds } from '@/static/js/staticData'
// ------------------------ 添加试驾和保养(表单)-开始 ------------------------
export const subscMixin = {
  data() {
    return {
      checkedVal: false,
      isTestDrive: true,
      inputStyles: { borderColor: '#ffffff', color: '#333333' },
      contactWaySelect: [
        { id: 1, value: '中國香港' },
        { id: 2, value: '中國澳門' },
        { id: 3, value: '中國內地' },
      ],
    }
  },
  methods: {
    change(e) {
      this.checkedVal = e
    },
    pushMsgChange(e) {
      this.testDriveaParam.promotion = e
    },
    centersChange(e, crm) {
      let temp = this.centers[e.detail.value]
      if (crm === 'crm') {
        this.centersList.forEach(item => {
          if (item.id === temp.crm_company_id) this.testDriveaParam.company_id = item.companyId
        })
      } else {
        this.testDriveaParam.company_id = temp.id
      }
      this.testDriveaParam.company = temp.value
    },
    contactWayChange(e) {
      let temp = this.contactWaySelect[e.detail.value]
      this.testDriveaParam.contactWay = temp.value
    },
    // 增加提交
    submit(ref) {

      let temp = cloneDeep(this.testDriveaParam)
      if (temp.type === 'A') {

        if (this.isHKAndMacao) {
          temp.phone_no = `${this.photoPrefix}${temp.phone_no}`
        }
      } else {
        if (this.isHKAndMacaoPhone) {
          temp.phone_no = `${this.photoPrefix}${temp.phone_no}`
        }
      }


      if (!this.checkedVal) {
        return uni.$showMsg('请阅读并同意勾选登录协议')
      }
      this.$refs[ref]
        .validate()
        .then(async (res) => {
          let { uuid } = this.loginInfo
          // let temp = this.testDriveaParam
          if (this.isHKAndMacao) {
            temp.address = ''
            temp.car_age = ''
            temp.industry = ''
          }
          temp.uuid = uuid
          console.log('temp :>> ', temp);
          // return
          const {
            data: { code, message },
          } = await addTestDrive(temp)
          if (code === 200) {
            uni.showToast({
              title: '预约成功!',
              mask: true,
            })
            this.checkedVal = false
            this.$refs[ref].clearValidate()
            // 模板ID
            let { testDrivea, maintain } = tmplIds
            if (temp.type == 'A') {
              this.testDrive.userInfo.data = { //该品牌新创了模板
                thing11: {
                  value: temp.name,
                },
                phone_number2: {
                  value: temp.phone_no,
                },
                thing1: {
                  value: temp.car_model,
                },
                thing7: {
                  value: temp.company,
                },
                thing8: {
                  value: '预约成功！等待客服电话联系确认试驾时间。',
                },
              }
              this.isTestDrive = true
              // 试驾预约
              this.testDriveaParam = {
                type: 'A',
                name: '',
                phone_no: '',
                address: '',
                curr_car_model: '',
                car_age: '',
                car_model: '',
                industry: '',
                company: '',
                company_id: '',
                brand_id,
                uuid: '',
                // -----
                email: '',//邮件
                promotion: '', //是否推广 // 推送消息
                remark_box: '',//备注
                visit_time: '', //到访时间
                // -----------
                way: '',
                contactWay: '',
              }
              uni.requestSubscribeMessage({
                //模板的模板ID
                tmplIds: [testDrivea],
                success: (res) => {

                  if (res[testDrivea] == 'accept') {
                    //  用户同意发送信息时
                    // 调用oppeId,api
                    this.getUserOpenid()
                  } else {
                    //  用户不同意发送信息时
                    // uni.$showMsg('授权失败')
                    uni.navigateTo({
                      url: '/pages/TestDrive/MyTestDrive',
                    })
                  }
                },
                fail: (err) => {
                  //  用户选择一直不要发送信息时
                  uni.navigateTo({
                    url: '/pages/TestDrive/MyTestDrive',
                  })
                },
              })
              console.log('object666 :>> ',);

            } else {
              this.isTestDrive = false
              this.maintainInfo.userInfo.data = {
                thing21: {
                  value: temp.name,
                },
                car_number24: {
                  value: temp.car_id,
                },
                date3: {
                  value: temp.appoint_time,
                },
                thing2: {
                  value: temp.company,
                },
                thing7: {
                  value: '预约成功！请您根据预约上门时间按时到店。',
                },
              }
              // 保养预约
              this.testDriveaParam = {
                type: 'M',
                name: '',
                phone_no: '',
                curr_kilo: '',
                car_id: '',
                appoint_time: '',
                service_type: '',
                company: '',
                company_id: '',
                remark: '',
                brand_id,
                uuid: '',
              }
              uni.requestSubscribeMessage({
                //模板的模板ID
                tmplIds: [maintain],
                success: (res) => {
                  if (res[maintain] == 'accept') {
                    //  用户同意发送信息时
                    // 调用oppeId,api
                    this.getUserOpenid()
                  } else {
                    //  用户不同意发送信息时
                    // uni.$showMsg('授权失败')
                    uni.navigateTo({
                      url: '/pages/CarMaintain/CarMaintain',
                    })
                  }
                },
                fail: (err) => {
                  //  用户选择一直不要发送信息时
                  uni.navigateTo({
                    url: '/pages/CarMaintain/CarMaintain',
                  })
                },
              })
            }
          }
        })
        .catch((err) => {
          console.log('err', err)
          uni.showToast({
            title: '请检查输入信息！',
            icon: 'none',
          })
        })
    },
    // 获取openId
    async getUserOpenid() {
      const [err, res] = await uni.login().catch((err) => err)
      if (err || res.errMsg !== 'login:ok')
        return uni.$showMsg('获取code失败！')
      const {
        data: { data, code },
      } = await getOpenIdApi({ brand, code: res.code })
      if (code === 200) {
        // 获取oppeId成功，调用发关送信息api
        if (this.isTestDrive) {
          // 调用试驾发送信息
          this.sendTestDrive(data.uuid)
        } else {
          // 调用保养发送信息
          this.sendMaintain(data.uuid)
        }
      }
    },
    // 试驾发送信息
    async sendTestDrive(oppeId) {
      this.testDrive.userInfo.touser = oppeId
      const { data } = await sendMessageApi(this.testDrive)
      if (data.code === 200) {
        uni.navigateTo({
          url: '/pages/TestDrive/MyTestDrive',
        })
      }
    },
    // 保养发送信息
    async sendMaintain(oppeId) {
      this.maintainInfo.userInfo.touser = oppeId
      const { data } = await sendMessageApi(this.maintainInfo)
      if (data.code === 200) {
        uni.navigateTo({
          url: '/pages/CarMaintain/CarMaintain',
        })
      }
    },
    // 按键被点击(
    valChange(val) {
      let tempVal = this.testDriveaParam.car_id
      if (this.isNew) {
        if (tempVal.length < 8) {
          this.testDriveaParam.car_id += val
        } else if (tempVal.length === 8) {
          this.plateShow = false
        }
      } else {
        if (tempVal.length < 7) {
          this.testDriveaParam.car_id += val
        } else if (tempVal.length === 7) {
          this.plateShow = false
        }
      }
    },
    // 退格键被点击
    backspace() {
      // 删除value的最后一个字符
      // if (this.carIdValue.length) this.carIdValue = this.carIdValue.substr(0, this.carIdValue.length - 1);
      let tempLen = this.testDriveaParam.car_id.length
      if (tempLen !== 0) {
        this.testDriveaParam.car_id = this.testDriveaParam.car_id.substr(
          0,
          tempLen - 1
        )
      } else {
        this.plateShow = false
      }
    },
    // 新源车牌
    clickNew() {
      if (!this.isNew) {
        this.plateShow = true
      }
      this.isNew = !this.isNew
      if (!this.isNew && this.testDriveaParam.car_id.length === 8) {
        this.testDriveaParam.car_id = this.testDriveaParam.car_id.substr(0, 7)
      }
    },
    // 调用子组件方法
    openRules() {
      this.$refs.rule.openRul()
    },
  },
}
// ------------------------ 预约试驾和维修保养(列表)-开始 ------------------------
export const carAppointListMixin = {
  data() {
    return {
      current: 0,
      totalPage: 0,
      testDriveList: [],
      status: 'loading',
      getListParam: {
        type: '',
        page: 1,
        pageSize: 20,
        brand_id,
        del_appoint: 0,
        task_complete: 0,
        uuid: '',
      },
    }
  },
  onLoad() {
    let { uuid } = this.loginInfo
    this.getListParam.type = this.type
    this.getListParam.uuid = uuid
    // 获取预约试驾，维修保养列表
    this.getTipsList()
  },
  methods: {
    onClickItem(e, type) {
      if (this.current === e) return false
      this.current = e
      this.getListParam.type = type
      this.getListParam.page = 1
      if (e === 1) {
        // this.getListParam.del_appoint = ''
        this.getListParam.task_complete = 1
      } else if (e === 0) {
        // this.getListParam.del_appoint = ''
        this.getListParam.task_complete = 0
      }
      this.testDriveList = []
      // 获取预约试驾，维修保养列表
      this.getTipsList()
    },
    // 预约试驾，维修保养列表
    async getTipsList() {
      const {
        data: { total, data },
      } = await testDrive(this.getListParam)
      this.totalPage = total
      this.testDriveList = data
      if (data.length >= total) {
        this.status = 'no-more'
      }
    },
  },
  computed: {
    ...mapState(['loginInfo']),
  }
}
